package com.xiang.ad.service.impl;

import com.xiang.ad.constant.Constants;
import com.xiang.ad.dao.AdUserRepository;
import com.xiang.ad.entity.AdUser;
import com.xiang.ad.exception.AdException;
import com.xiang.ad.service.UserService;
import com.xiang.ad.utils.CommonUtils;
import com.xiang.ad.vo.CreateUserRequest;
import com.xiang.ad.vo.CreateUserResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by xiang.
 * 用户服务 实现类
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private final AdUserRepository userRepository;//注入dao

    @Autowired
    public UserServiceImpl(AdUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    //创建用户
    @Override
    @Transactional //开启事务
    public CreateUserResponse createUser(CreateUserRequest request)
            throws AdException {
        //验证参数，这里只有username非空验证
        if (!request.validate()) {
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        //验证参数，username的重复验证
        AdUser oldUser = userRepository.
                findByUsername(request.getUsername());
        if (oldUser != null) {
            throw new AdException(Constants.ErrorMsg.SAME_NAME_ERROR);
        }
        //验证通过后，创建user，传入username 和 token，其他三个
        AdUser newUser = userRepository.save(new AdUser(
                request.getUsername(),
                CommonUtils.md5(request.getUsername())  //简单给一个token，用md5实现，可以用其他的方式生成token
        ));

        //
        return new CreateUserResponse(
                newUser.getId(), newUser.getUsername(), newUser.getToken(),
                newUser.getCreateTime(), newUser.getUpdateTime()
        );
    }
}
